package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import vo.Upload;

public class UploadDAO {
	
	public List<Upload> findAll(){
		List<Upload> list=new ArrayList<>();
		String sql="select * from upload";
		Connection conn = ConnectionFactory.getConnection();
		Statement stmt;
		try {
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while(rs.next()){
				String path = "1.jpg";
				Upload u=new Upload(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4),path);
				list.add(u);
			}
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	public Upload findById(Integer id){
		String sql="select * from upload t where id="+id;
		Upload upload=null;
		Connection conn = ConnectionFactory.getConnection();
		Statement stmt;
		try {
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if(rs.next()){
				String path = "1.jpg";
				upload=new Upload(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4),path);
			}
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return upload;
	}
	
	public synchronized void save(Upload upload){
		String sql1="insert into upload values(null,?,?,?)";
		String sql2="update upload set filename=?,notes=?,uuid=? where id=?";
		Connection conn = ConnectionFactory.getConnection();
		PreparedStatement pstmt;
		try {
			if(upload.getId()==null){
					pstmt = conn.prepareStatement(sql1);
					pstmt.setString(1, upload.getFilename());
					pstmt.setString(2, upload.getNotes());
					pstmt.setString(3, upload.getUuid());
					pstmt.execute();
					Statement stmt = conn.createStatement();
					ResultSet rs = stmt.executeQuery("select * from upload order by id desc");
					if(rs.next()){
						upload.setId(rs.getInt(1));
					}
			}else{
				pstmt = conn.prepareStatement(sql2);
				pstmt.setString(1, upload.getFilename());
				pstmt.setString(2, upload.getNotes());
				pstmt.setString(3, upload.getUuid());
				pstmt.setInt(4, upload.getId());
				pstmt.execute();
			}
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void delete(Integer id) {
		String sql="delete from upload where id="+id;
		Connection conn = ConnectionFactory.getConnection();
		Statement stmt;
		try {
			stmt = conn.createStatement();
			stmt.execute(sql);
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
}
